package simplyothello.facebook;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.restfb.Connection;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.types.User;

public class SimplyOthelloServerlet extends HttpServlet {

	private FacebookClient facebookClient;

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String signedRequest = request.getParameter("signed_request");
		FacebookSignedRequest facebookSR = null;
		try {
			facebookSR = FacebookSignedRequest
					.getFacebookSignedRequest(signedRequest);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String oauthToken = facebookSR.getOauth_token();
		PrintWriter writer = response.getWriter();
		if (oauthToken == null) {

			response.setContentType("text/html");
			String authURL = "https://www.facebook.com/dialog/oauth?client_id="
					+ Constants.API_KEY
					+ "&redirect_uri=https://apps.facebook.com/simplyothello/&scope=";
			writer.print("<script> top.location.href='" + authURL
					+ "'</script>");
			writer.close();

		} else {
			// Answer for code here

			facebookClient = new DefaultFacebookClient(oauthToken);
			Connection<User> myFriends = facebookClient.fetchConnection(
					"me/friends", User.class);
			writer.print("<P>");
			writer.print("Hello World!!");
			writer.print("</P>");
			writer.close();

		}

	}

}
